package com.geek.projects.user.repository;

import com.geek.projects.user.domain.User;
import com.geek.projects.user.sql.DBConnectionManager;
import com.geek.projects.utils.RepositoryHandleUtil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;


public class UserRepositoryImpl implements UserRepository {

    private static Logger logger = Logger.getLogger(UserRepositoryImpl.class.getName());

    public static final String CREATE_USERS_TABLE_DDL_SQL = "CREATE TABLE users(" +
            "id INT NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), " +
            "name VARCHAR(16) NOT NULL, " +
            "password VARCHAR(64) NOT NULL, " +
            "email VARCHAR(64) NOT NULL, " +
            "phoneNumber VARCHAR(64) NOT NULL" +
            ")";


    public UserRepositoryImpl() {
        initTable();
    }

    private void initTable() {
        try {
            Connection connection = getConnection();
            Statement statement = connection.createStatement();
            statement.execute(CREATE_USERS_TABLE_DDL_SQL);
        } catch (SQLException e) {
            //如果创建表出现异常,直接忽略
        }
    }

    /**
     * 通用处理方式
     */
    private static Consumer<Throwable> COMMON_EXCEPTION_HANDLER = e -> logger.log(Level.SEVERE, e.getMessage());

    private Connection getConnection() throws SQLException {
        DBConnectionManager dbConnectionManager =
                new DBConnectionManager(DriverManager
                        .getConnection("jdbc:derby:user-platform;create=true"));
        return dbConnectionManager.getConnection();
    }

    private static final String QUERY_USER_DML_SQL =
            "SELECT id,name,password,email,phoneNumber FROM users WHERE name=? and password=?";

    private static final String INSERT_USER_DML_SQL =
            "INSERT INTO users(name,password,email,phoneNumber) VALUES " +
                    "(?,?,?,?)";

    @Override
    public User queryOne(User user) throws SQLException {
        return RepositoryHandleUtil.executeQuery(QUERY_USER_DML_SQL, resultSet -> {
            List<User> users = RepositoryHandleUtil.handleResultSetList(new User(), resultSet);
            if (!users.isEmpty()) {
                return users.get(0);
            }
            return null;
        }, COMMON_EXCEPTION_HANDLER, getConnection(), user.getName(), user.getPassword());
    }


    @Override
    public boolean save(User user) throws SQLException {
        Integer count = RepositoryHandleUtil.executeInsert(COMMON_EXCEPTION_HANDLER, getConnection(), user);
        return count > 0;
    }
}
